#include "titlebar.h"

#include <QSizeGrip>
#include <iostream>


/***************************            构造函数              ***************************/
TitleBar::TitleBar(QWidget *parent) : QFrame(parent)
{


    //设置父类窗口
    parentWidget = parent;
    //初始化参数
    initData();
    //初始化按钮
    initBotton();
    //初始化
    initConnect();
    //设置标题栏背景色
    set_ChildWindowColor(70, 70, 70);
    //设置标题栏显示文字颜色
    SetTitleLabelTextColor(255, 255, 255);
    //重置窗口大小
    //resize(parent->width(), TITLEBARHEIGHT);
    //setFixedHeight(TITLEBARHEIGHT);
    //设置阴影
    //Shadow_Warning();
}

void TitleBar::initData()
{
    switchFlag = 1;
    MaximizeFlag = 0;
    isTitleBarResize = true;
    IsShow_Toolbar = 1;
    this->setMouseTracking(true);
    this->setAttribute(Qt::WA_Hover, true);
    this->installEventFilter(this);
    isLeftPressDown = false;
    this->dir = NONE;
}
void TitleBar::initBotton()
{
    //最大化按钮设置图标
    maxButton = new QPushButton(this);
    maxButton->setFocusPolicy(Qt::NoFocus);
    maxButton->setIcon(QPixmap(":/icon/images/max.png"));

    //最小化按钮设置图标
    minButton = new QPushButton(this);
    minButton->setFocusPolicy(Qt::NoFocus);
    minButton->setIcon(QPixmap(":/icon/images/minus.png"));

    //关闭按钮设置图标
    closeButton = new QPushButton(this);
    closeButton->setShortcut(tr("Ctrl+w"));
    closeButton->setFocusPolicy(Qt::NoFocus);
    closeButton->setIcon(QPixmap(":/icon/images/close.png"));

    //设置标签
    imgLabel = new QLabel(this);
    imgLabel->setScaledContents(true);
    imgLabel->setStyleSheet("color:white");
    imgLabel->setPixmap(QPixmap(":/icon/images/017.GIF"));
    titleLabel = new QLabel(this);
    titleLabel->setText(tr("雷达监控系统"));
    titleLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);

    //设置控件大小
    imgLabel->setFixedSize(CONTROLWIDTH, CONTROLWIDTH);
    imgLabel->setScaledContents(true);
    titleLabel->setMinimumSize(120, TITLEBARHEIGHT);
    //    minButton->setFixedSize(CONTROLWIDTH, CONTROLWIDTH);
    //    maxButton->setFixedSize(CONTROLWIDTH, CONTROLWIDTH);
    //    closeButton->setFixedSize(CONTROLWIDTH, CONTROLWIDTH);

    //设置控件图标大小
    //    minButton->setIconSize(QSize(CONTROLWIDTH, CONTROLWIDTH));
    //    maxButton->setIconSize(QSize(CONTROLWIDTH, CONTROLWIDTH));
    //    closeButton->setIconSize(QSize(CONTROLWIDTH, CONTROLWIDTH));

    //设置鼠标移至按钮上的提示信息
    ModifyTitleBarTip();

    //设置布局
    QHBoxLayout *hBoxLayout = new QHBoxLayout;
    hBoxLayout->addSpacing(5);
    hBoxLayout->addWidget(imgLabel);
    hBoxLayout->addSpacing(5);
    hBoxLayout->addWidget(titleLabel);
    hBoxLayout->addStretch();
    hBoxLayout->addSpacing(5);
    hBoxLayout->addWidget(minButton);
    hBoxLayout->addWidget(maxButton);
    hBoxLayout->addWidget(closeButton);
    hBoxLayout->setSpacing(0);
    hBoxLayout->setContentsMargins(0, 0, 2, 0);
    this->setLayout(hBoxLayout);
}

/***************************            设置标题              ***************************/
void TitleBar::setWindowTitle(const QString &title)
{
    QFont myFont;
    //设置文字大小
    myFont.setPointSize(12);
    //设置文字字体
    myFont.setFamily(qApp->font().family());
    titleLabel->setFont(myFont);
    titleLabel->setText(title);
}

/***************************            设置图标              ***************************/
void TitleBar::setWindowIcon(const QString &icon)
{
    if (icon.isEmpty())
        imgLabel->hide();
    else
        imgLabel->setPixmap(QPixmap(icon));
}

/***************************            设置标题栏不需要显示的按钮              ***************************/
void TitleBar::subWindowButton(const int &type)
{
    if(type == TITLEBAR::MINWIDGET)
    {
        SAFEDELETE(minButton);
    }
    else if(type == TITLEBAR::MAXWIDGET)
    {
        SAFEDELETE(maxButton);
    }
    else if(type == TITLEBAR::CloseWIDGET)
    {
        SAFEDELETE(closeButton);
    }
    else if(type == TITLEBAR::ALLWIDGET)
    {
        SAFEDELETE(minButton);
        SAFEDELETE(maxButton);
    }
    else if (type == TITLEBAR::NOBUTTON)
    {
        SAFEDELETE(minButton);
        SAFEDELETE(maxButton);
        SAFEDELETE(closeButton);
    }
}

void TitleBar::Shadow_Warning()
{
    //窗口添加阴影效果
    QGraphicsDropShadowEffect *shadow_effect = new QGraphicsDropShadowEffect;
    shadow_effect->setOffset(0, 4);
    shadow_effect->setColor(Qt::gray);
    shadow_effect->setBlurRadius(6);
    this->setGraphicsEffect(shadow_effect);

    //实现毛玻璃效果
    QGraphicsBlurEffect* ef = new QGraphicsBlurEffect;
    ef->setBlurRadius(1.5);
    ef->setBlurHints(QGraphicsBlurEffect::AnimationHint);
    this->setGraphicsEffect(ef);

}

//移除最大最小按钮
void TitleBar::RemoveMaxMinButton()
{
    subWindowButton(TITLEBAR::ALLWIDGET);
}

//设置双击标题栏是否可以最大、最小化
void TitleBar::Set_MaximizeFlag()
{
    MaximizeFlag = 1;
}
//文件是否存在
bool TitleBar::FileIsExist(QString strFile)
{
    QFile tempFile(strFile);
    return tempFile.exists();
}
//修改标题显示文字颜色
void TitleBar::SetTitleLabelTextColor(int R,int G,int B)
{
    titleLabel->setStyleSheet(QString("QLabel{background-color:transparent;color:rgb(%1,%2,%3);outline: none;border:none;qproperty-alignment: 'AlignVCenter | AlignLeft';}").arg(R).arg(G).arg(B));
}

/***************************            初始化              ***************************/
void TitleBar::initConnect()
{
    //设置样式表
    minButton->setStyleSheet("QPushButton{background-color:transparent;outline: none;border:none;}QPushButton:hover{padding-left:6px;padding-top:6px;}");
    maxButton->setStyleSheet("QPushButton{background-color:transparent;outline: none;border:none;}QPushButton:hover{padding-left:6px;padding-top:6px;}");
    closeButton->setStyleSheet("QPushButton{background-color:transparent;outline: none;border:none;border-radius: 0px;}QPushButton:hover{padding-left:6px;padding-top:6px;background-color:rgb(237,28,36);}");
    //连接信号与槽
    connect(minButton,              SIGNAL(clicked(bool)), this, SLOT(showMin()));
    connect(maxButton,              SIGNAL(clicked(bool)), this, SLOT(showMax()));
    connect(closeButton,            SIGNAL(clicked(bool)), this, SLOT(showClose()));
}


/***************************            最大化              ***************************/
void TitleBar::showMax()
{
    if(parentWidget->geometry() == QApplication::desktop()->availableGeometry()) //判断是否是全屏
    {
        maxButton->setIcon(QPixmap("style/icons/max.png"));
        //退出全屏时设置为原窗口的坐标位置和尺寸大小
        parentWidget->setGeometry(Original_window_x, Original_window_y, Original_window_Mywidth, Original_window_Myheight);
    }
    else
    {
        //但不是全屏时获取原窗口的坐标和尺寸
        Original_window_x           = parentWidget->geometry().x();
        Original_window_y           = parentWidget->geometry().y();
        Original_window_Mywidth     = parentWidget->geometry().width();
        Original_window_Myheight    = parentWidget->geometry().height();
        maxButton->setIcon(QPixmap("style/icons/normal.png"));
        parentWidget->setGeometry(QApplication::desktop()->availableGeometry());            //这种设置不会全屏遮挡任务栏
    }
}

/***************************            最小化              ***************************/
void TitleBar::showMin()
{
    parentWidget->showMinimized();
}

/***************************      发送关闭信号给主窗口        ***************************/
void TitleBar::showClose()
{

    emit send_close();
}

void TitleBar::set_ChildWindowColor(int R,int G,int B)
{
    //设置背景色
    setStyleSheet(QString("QFrame{background-color:rgb(%1,%2,%3);outline: none;border:none;}").arg(R).arg(G).arg(B));
}

//修改标题栏按钮提示语言
void TitleBar::ModifyTitleBarTip()
{
    //设置鼠标移至按钮上的提示信息
    minButton->setToolTip(tr(u8"最小化"));
    maxButton->setToolTip(tr(u8"最大化"));
    closeButton->setToolTip(tr(u8"关闭"));
}


/***************************           鼠标点击             ***************************/
void TitleBar::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        isLeftPressDown = true;
        if (isTitleBarResize)
            setMousePressCursorShape(event->pos());
        if (dir != NONE) {
            this->mouseGrabber();
        }
        else {
            movePoint = event->globalPos() - parentWidget->pos();
        }
    }
}

/**************************             鼠标释放              ***************************/
void TitleBar::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        isLeftPressDown = false;
        if (dir != NONE) {
            dir = NONE;
            this->releaseMouse();
            this->setCursor(QCursor(Qt::ArrowCursor));
        }
    }
}

/**************************             鼠标移动              **************************/
void TitleBar::mouseMoveEvent(QMouseEvent *event)
{
    if(parentWidget->geometry() == QApplication::desktop()->availableGeometry())
    {
        //判断当前是全屏就不允许拖动窗口
    }
    else
    {
        //当前不是全屏可以拖动窗口
        QPoint gloPoint = event->globalPos();
        QRect rect = parentWidget->rect();
        QPoint tl = mapToGlobal(rect.topLeft());
        QPoint rb = mapToGlobal(rect.bottomRight());

        if (!isLeftPressDown) {
            if (isTitleBarResize)
                setMousePressCursorShape(gloPoint);
        }
        else {

            if (dir != NONE) {
                QRect rMove(tl, rb);

                switch (dir) {
                case LEFT:
                    if (rb.x() - gloPoint.x() <= parentWidget->minimumWidth())
                        rMove.setX(tl.x());
                    else
                        rMove.setX(gloPoint.x());
                    break;
                case RIGHT:
                    rMove.setWidth(gloPoint.x() - tl.x());
                    break;
                case UP:
                    if (rb.y() - gloPoint.y() <= parentWidget->minimumHeight())
                        rMove.setY(tl.y());
                    else
                        rMove.setY(gloPoint.y());
                    break;
                case LEFTTOP:
                    if (rb.x() - gloPoint.x() <= parentWidget->minimumWidth())
                        rMove.setX(tl.x());
                    else
                        rMove.setX(gloPoint.x());
                    if (rb.y() - gloPoint.y() <= parentWidget->minimumHeight())
                        rMove.setY(tl.y());
                    else
                        rMove.setY(gloPoint.y());
                    break;
                case RIGHTTOP:
                    rMove.setWidth(gloPoint.x() - tl.x());
                    if (rb.y() - gloPoint.y() <= parentWidget->minimumHeight())
                        rMove.setY(tl.y());
                    else
                        rMove.setY(gloPoint.y());
                    break;
                default:
                    break;
                }
                parentWidget->setGeometry(rMove);
            }
            else {
                QPoint movePos = event->globalPos();
                parentWidget->move(movePos - movePoint);
                if(parentWidget->pos().y() <= 0) parentWidget->move(parentWidget->x(), 0);
                if(parentWidget->pos().y() + this->height() >= QApplication::desktop()->availableGeometry().height())
                    parentWidget->move(parentWidget->x(), QApplication::desktop()->availableGeometry().height() - this->height());
                event->accept();
            }
        }
    }
}

/**************************            鼠标双击               **************************/
void TitleBar::mouseDoubleClickEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        if(MaximizeFlag == 1)
        {
            int x = event->x();
            int y = event->y();
            if((x > 0 && x < parentWidget->width()) && (y > 0 && y < TITLEBARHEIGHT)) //如果双击的范围在标题栏的范围之内
            {
                showMax(); //调用全屏、退出全屏函数
            }
        }
    }
}

bool TitleBar::eventFilter(QObject * obj, QEvent * event)
{
    if (obj == this)
    {
        if (event->type() == QMouseEvent::HoverEnter)
        {
            QMouseEvent *_mouseEvent = static_cast<QMouseEvent *>(event);
            if (isTitleBarResize)
                setMousePressCursorShape(_mouseEvent->pos(), false);
        }
        if (event->type() == QMouseEvent::HoverMove)
        {
            QMouseEvent *_mouseEvent = static_cast<QMouseEvent *>(event);
            if (!isLeftPressDown)
            {
                if (isTitleBarResize)
                    setMousePressCursorShape(_mouseEvent->pos(), false);
            }
        }
        if (event->type() == QMouseEvent::HoverLeave)
        {
            if (isTitleBarResize)
                unsetCursor();
        }
    }
    return QFrame::eventFilter(obj, event);
}

void TitleBar::Set_MouseShapeFlag(bool MouseShape)
{
    isTitleBarResize = MouseShape;
}

QRectF TitleBar::boundingRect() const
{
    return QRectF(QPointF(0, 0), geometry().size());
}

QRectF TitleBar::leftBorder() const
{
    return QRectF(0, 0, PADDING, boundingRect().height());
}

QRectF TitleBar::rightBorder() const
{
    return QRectF(boundingRect().width() - PADDING, 0, PADDING, boundingRect().height());
}

QRectF TitleBar::topBorder() const
{
    return QRectF(0, 0, boundingRect().width(), PADDING);
}

QRectF TitleBar::bottomBorder() const
{
    return QRectF(0, boundingRect().height() - PADDING, boundingRect().width(), PADDING);
}

void TitleBar::setMousePressCursorShape(const QPointF& pt, bool isShow)
{
    QCursor cursor = Qt::ArrowCursor;
    if (rightBorder().contains(pt) && topBorder().contains(pt))        // 右上角
    {
        if(isShow)
            dir = RIGHTTOP;
        this->setCursor(QCursor(Qt::SizeBDiagCursor));
    }
    else if (leftBorder().contains(pt) && topBorder().contains(pt))         // 左上角
    {
        if (isShow)
            dir = LEFTTOP;
        this->setCursor(QCursor(Qt::SizeFDiagCursor));
    }
    else if (rightBorder().contains(pt))        // 右边
    {
        if (isShow)
            dir = RIGHT;
        this->setCursor(QCursor(Qt::SizeHorCursor));
    }
    else if (leftBorder().contains(pt))         // 左边
    {
        if (isShow)
            dir = LEFT;
        this->setCursor(QCursor(Qt::SizeHorCursor));
    }
    else if (topBorder().contains(pt))          // 上边
    {
        if (isShow)
            dir = UP;
        this->setCursor(QCursor(Qt::SizeVerCursor));
    }
    else
    {
        if (isShow)
            dir = NONE;
        this->setCursor(QCursor(isLeftPressDown ? Qt::SizeAllCursor : Qt::ArrowCursor));
    }
}

// 绘制事件中设置标题栏宽度跟随父窗口宽度变化尺寸
void TitleBar::paintEvent(QPaintEvent *event)
{
    if (this->width() != parentWidget->width())
    {
        this->setFixedWidth(parentWidget->width());
    }
    QFrame::paintEvent(event);
}



